package com.yunbao.ioc.tx;

import java.lang.reflect.Method;
import java.util.Set;

/**
 * Created by louisyuu on 2020/3/4 下午3:06
 */
public abstract class TransactionAdvisor {


    private TransactionManager transactionManager;

    private Object target;


    public TransactionAdvisor(TransactionManager transactionManager, Object target) {
        this.transactionManager = transactionManager;
        this.target = target;
    }

    protected Object invoke(Method method, Object[] args) throws Throwable {
        Set<Method> adviceMethods = TransactionalAdviceInfo.getAdviceMethods(method.getDeclaringClass());
        Object result;

        if (adviceMethods.contains(method)) {
            try {
                transactionManager.beganTransaction();
                result = method.invoke(target, args);
                transactionManager.commitTransaction();
            } catch (Exception e) {
                transactionManager.rollback();
                throw e;
            }
        } else {
            result = method.invoke(target, args);
        }
        return result;
    }


    public TransactionManager getTransactionManager() {
        return transactionManager;
    }

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    public Object getTarget() {
        return target;
    }

    public void setTarget(Object target) {
        this.target = target;
    }
}
